#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;


int flg = 0;

void* run(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mtx);
        if (!flg)
        {
            flg = 1;
            // printf("%s陷入等待\n",name.c_str());
            pthread_cond_wait(&cond,&mtx); //被唤醒之后又要重新生成锁
            // printf("%s被唤醒\n",name.c_str());
        }
        printf("我是%s\n", name.c_str());
        sleep(1);

        flg = 0;
        pthread_cond_signal(&cond);
        
        pthread_mutex_unlock(&mtx);

    }
    return nullptr;
}

int main()
{

    pthread_t tid1;
    pthread_t tid2;

    pthread_create(&tid1,nullptr,run,(void*)"线程A");
    pthread_create(&tid1,nullptr,run,(void*)"线程B");

    pthread_join(tid1,nullptr);
    pthread_join(tid2,nullptr);
    return 0;
}